package com.atguigu.aiproject.config;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SseConnectionManager {

    private final Map<String, SseEmitter> connections = new ConcurrentHashMap<>();//存储会话的映射关系
    private final MeterRegistry meterRegistry;//用于记录当前活跃的连接数
    public SseConnectionManager(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    public void addConnection(String sessionId, SseEmitter emitter) {
        // 将会话ID和对应的SseEmitter对象存储到connections映射中
        connections.put(sessionId, emitter);
        // 在监控系统中注册一个名为"sse.connections"的计量器，用来跟踪当前SSE连接数
        meterRegistry.gauge("sse.connections", connections.size());
        //注册两个回调函数
        // 当连接完成时，调用removeConnection方法移除该连接
        emitter.onCompletion(() -> removeConnection(sessionId));
        // 当连接超时时，调用removeConnection方法移除该连接
        emitter.onTimeout(() -> removeConnection(sessionId));
    }

    public void removeConnection(String sessionId) {
        connections.remove(sessionId);
        meterRegistry.gauge("sse.connections", connections.size());
    }

    public int getActiveConnections() {
        return connections.size();
    }
}
